﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using HumanResorcesProj.BLL;

namespace HumanResorcesProj.GUI.Extensions
{
  

    /// <summary>
    /// Handles uploading- and storing a file in a database.
    /// </summary>
    public partial class UploadFile : System.Web.UI.Page
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            btnUploadFile.Click += new EventHandler(btnUploadFile_Click);
        }
        void btnUploadFile_Click(object sender, EventArgs e)
        {
            // exit if file-upload has no file
            if (!ctrFile.HasFile) return;

            // generate new fileId
            Guid fileId = Guid.NewGuid();
            // create insert query
            using (SqlCommand command = new SqlCommand())
            {
                command.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Eden-DatabaseConnectionString3"].ConnectionString);
                command.CommandText = @"insert into [File](FileId, FileName, FileType, FileSize, FileContent, UserId)
						values(@FileId, @FileName, @FileType, @FileSize, @FileContent, @UserId)";
                command.Parameters.Add("@FileId", SqlDbType.UniqueIdentifier).Value = fileId;
                command.Parameters.Add("@FileName", SqlDbType.NVarChar, 100).Value = Path.GetFileName(ctrFile.PostedFile.FileName);
                command.Parameters.Add("@FileType", SqlDbType.NVarChar, 100).Value = ctrFile.PostedFile.ContentType;
                command.Parameters.Add("@FileSize", SqlDbType.Int).Value = ctrFile.PostedFile.ContentLength;
                command.Parameters.Add("@UserId", SqlDbType.NVarChar,  9).Value = ctrFile.PostedFile.ContentLength;
                // filecontent, convert from stream to byte array
                byte[] fileContent = new byte[ctrFile.PostedFile.ContentLength];
                ctrFile.PostedFile.InputStream.Read(fileContent, 0, ctrFile.PostedFile.ContentLength);
                command.Parameters.Add("@FileContent", SqlDbType.VarBinary, -1).Value = fileContent;
                command.Connection.Open();
                command.ExecuteNonQuery();
            }
            // show result
            ctrResult.NavigateUrl = "FileStream.ashx?FileId=" + fileId.ToString();
            ctrResult.Text = "Click here to view the uploaded file";
        }
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //  BLL.CurrEmp TheSelectetFile = GridView1.SelectedDataKey.ToString();
        }
        protected void Page_Load(object sender, EventArgs e)
        {

        }
}

}
